<template>
    <div class="container">
        <!-- 用户管理 -->
        <div class="userManageMain">
            <el-form
                :inline="true"
                :model="formData"
                class="demo-form-inline formData_form_inline"
                size="small"
            >
                <el-form-item label="用户账号">
                    <el-input v-model="formData.userAccount" placeholder="请输入用户账号"></el-input>
                </el-form-item>
                <el-form-item label="用户名称">
                    <el-input v-model="formData.userName" placeholder="请输入用户名称"></el-input>
                </el-form-item>
                <!--<el-form-item label="所属职场">-->
                <!--<el-select v-model="formData.workplaceId" clearable placeholder="请选择所属职场">-->
                <!--<el-option-->
                <!--v-for="(item, index) in workplaceList"-->
                <!--:key="index"-->
                <!--:label="item.workplaceName"-->
                <!--:value="item.id"-->
                <!--/>-->
                <!--</el-select>-->
                <!--</el-form-item>-->
                <el-form-item label="话务工号">
                    <el-input v-model="formData.ctiNum" placeholder="请输入话务工号"></el-input>
                </el-form-item>
                <el-button
                    type="primary"
                    size="small"
                    icon="el-icon-search"
                    @click="hanlesearch"
                    :loading="searchLoading"
                >查 询</el-button>
                <el-button
                    type="primary"
                    size="small"
                    icon="el-icon-refresh-right"
                    @click="handleReset"
                    :loading="resetLoading"
                >重 置</el-button>
            </el-form>
            <div style="margin-bottom: 16px">
                <el-button
                    type="primary"
                    size="small"
                    icon="el-icon-circle-plus-outline"
                    @click="hanlePush"
                >新增</el-button>
                <el-button
                    type="primary"
                    size="small"
                    icon="el-icon-circle-plus-outline"
                    @click="clickImport"
                >批量导入</el-button>
                <el-button
                    type="primary"
                    size="small"
                    icon="el-icon-download"
                    @click="downloadFile"
                >点击下载导入模板</el-button>
            </div>
            <el-table :data="tableData" width="100%" stripe border class="heard-bg">
                <el-table-column
                    label="用户账号"
                    prop="userAccount"
                    width="140px"
                    show-overflow-tooltip
                ></el-table-column>
                <el-table-column label="用户名称" prop="userName" width="160px" show-overflow-tooltip></el-table-column>
                <el-table-column label="系统话务工号" prop="ctiNum" width="140px" show-overflow-tooltip></el-table-column>
                <el-table-column label="所属机构" prop="deptName" width="200px" show-overflow-tooltip></el-table-column>
                <!--<el-table-column label="用户类型">-->
                <!--<template slot-scope="scope">-->
                <!--<span v-if="scope.row.userType === '0'">普通用户</span>-->
                <!--&lt;!&ndash;<span v-else-if="scope.row.userType === '1'">超级管理员</span>&ndash;&gt;-->
                <!--<span v-else-if="scope.row.userType === '2'">超级管理员</span>-->
                <!--</template>-->
                <!--</el-table-column>-->
                <el-table-column label="所属团队" prop="teamStr" width="200px" show-overflow-tooltip></el-table-column>
                <!--<el-table-column label="技能组话务级别" prop="skillLevel"></el-table-column>-->
                <!--<el-table-column label="服务级别" prop="serverLevel"></el-table-column>-->
                <el-table-column label="角色权限" prop="roleStr" show-overflow-tooltip></el-table-column>
                <el-table-column label="建立时间" prop="createTime"></el-table-column>
                <!--<el-table-column label="状态">-->
                <!--<template slot-scope="scope">-->
                <!--<span v-if="scope.row.userStatus === 'normal'">正常 </span>-->
                <!--<span v-else-if="scope.row.userStatus === 'freeze'">冻结 </span>-->
                <!--<span v-else-if="scope.row.userStatus === 'del'">已删除 </span>-->
                <!--</template>-->
                <!--</el-table-column>-->
                <el-table-column label="修改时间" prop="updateTime"></el-table-column>
                <el-table-column label="操作" width="140px">
                    <template slot-scope="scope">
                        <el-button
                            type="primary"
                            icon="el-icon-edit"
                            circle
                            title="编辑"
                            @click="handleEdit(scope.row)"
                        />
                        <el-button
                            type="primary"
                            icon="el-icon-key"
                            v-if="resetFlag"
                            circle
                            title="密码重置"
                            @click="handleResetPass(scope.row)"
                        />
                        <el-button
                            type="danger"
                            icon="el-icon-delete"
                            circle
                            title="删除"
                            @click="handleDelete(scope.row)"
                        />
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <div class="pagination">
                <Pagination
                    :hanleChangeCurrentPage="hanleChangeCurrentPage"
                    :handleChangeSize="handleChangeSize"
                    :currentPage="currentPage"
                    :pageSize="pageSize"
                    :total="total"
                />
            </div>
        </div>
        <el-dialog
            v-drag
            :close-on-click-modal="false"
            :visible.sync="Show"
            append-to-body
            center
            width="550px"
        >
            <div slot="title">{{ EditTitle }}</div>
            <el-form
                :model="Edit"
                class="menu-setting"
                label-position="right"
                ref="Edit"
                label-width="130px"
                :rules="formRules"
                size="small"
            >
                <el-form-item label="用户账号" prop="userAccount">
                    <el-input
                        v-model="Edit.userAccount"
                        placeholder="请输入用户账号"
                        :disabled="editFlag"
                    />
                </el-form-item>
                <el-form-item label="用户名称" prop="userName">
                    <el-input v-model="Edit.userName" placeholder="请输入用户名称" />
                </el-form-item>
                <el-form-item label="是否党员" prop="labelCommunist">
                    <el-radio label="1" v-model="Edit.labelCommunist" border>是</el-radio>
                    <el-radio label="0" v-model="Edit.labelCommunist" border>否</el-radio>
                </el-form-item>
                <!--<el-form-item label="所属职场" prop="workplaceId">-->
                <!--<el-select-->
                <!--v-model="Edit.workplaceId"-->
                <!--clearable-->
                <!--placeholder="请选择所属职场"-->
                <!--&gt;-->
                <!--<el-option-->
                <!--v-for="(item, index) in workplaceList"-->
                <!--:key="index"-->
                <!--:label="item.workplaceName"-->
                <!--:value="item.id"-->
                <!--/>-->
                <!--</el-select>-->
                <!--</el-form-item>-->
                <el-form-item label="所属机构" prop="deptId">
                    <select-tree v-model="Edit.deptId" :options="departList" :props="defaultProps"></select-tree>
                </el-form-item>
                <el-form-item label="用户类型" prop="userType">
                    <el-select v-model="Edit.userType" clearable placeholder="请选择用户类型">
                        <el-option label="普通用户" v-if="customerFlag" value="0" />
                        <!--<el-option label="超级管理员" :disabled="!(Edit.userType === '1' || !Edit.id)" value="1"/>-->
                        <el-option label="超级管理员" v-if="lesseeFlag" value="2" />
                    </el-select>
                </el-form-item>
                <el-form-item label="AG工号" prop="agNum">
                    <el-input v-model="Edit.agNum" placeholder="请输入" :disabled="true" />
                </el-form-item>
                <el-form-item label="系统话务工号" prop="ctiNum">
                    <el-input v-model="Edit.ctiNum" placeholder="请输入系统话务工号" />
                </el-form-item>
                <el-form-item label="服务级别:" class="text_fl">
                    <el-select v-model="Edit.serverLevel" placeholder="请选择服务级别">
                        <el-option
                            v-for="item in serverLevelOption"
                            :label="item.label"
                            :value="item.code"
                            :key="item.code"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <!--<el-form-item label="CTI工号登录密码" prop="ctiPass">-->
                <!--<el-input v-model="Edit.ctiPass" placeholder="请输入"  />-->
                <!--</el-form-item>-->
                <!--<el-form-item label="分机号" prop="extensionNum">-->
                <!--<el-input v-model="Edit.extensionNum" placeholder="请输入" />-->
                <!--</el-form-item>-->
                <!--<el-form-item label="技能组话务级别" prop="skillLevel">-->
                <!--<el-input v-model="Edit.skillLevel" placeholder="请选择技能组话务级别" />-->
                <!--</el-form-item>-->
                <el-form-item label="手机号" prop="userPhone">
                    <el-input v-model="Edit.userPhone" placeholder="请输入手机号" />
                </el-form-item>
                <el-form-item label="邮箱" prop="userEmail">
                    <el-input v-model="Edit.userEmail" placeholder="请输入邮箱" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button
                    size="small"
                    icon="el-icon-circle-close"
                    @click="Show = false"
                    class="cancelBtn"
                >取 消</el-button>
                <el-button
                    type="primary"
                    size="small"
                    @click="submitEdit"
                    class="submitBtn"
                    icon="el-icon-circle-check"
                >确定</el-button>
            </div>
        </el-dialog>

        <!--批量导入-->
        <el-dialog
            v-drag
            :close-on-click-modal="false"
            :visible.sync="importShow"
            append-to-body
            center
            width="500px"
            @close="cancelClick"
        >
            <div slot="title">用户数据批量导入</div>
            <YsUpload ref="YsUpload" :actionUrl="actionUrl" @getInitData="getInitData"></YsUpload>
            <div slot="footer" class="dialog-footer">
                <el-button
                    size="small"
                    icon="el-icon-circle-close"
                    @click="cancelClick"
                    class="cancelBtn"
                >取 消</el-button>
                <el-button
                    type="primary"
                    size="small"
                    @click="handleImport"
                    class="submitBtn"
                    icon="el-icon-circle-check"
                    :disabled="false"
                >确定</el-button>
            </div>
        </el-dialog>
        <!--导入模板说明-->
        <el-dialog
            v-drag
            :close-on-click-modal="false"
            :visible.sync="ShowImportTemp"
            append-to-body
            center
            height="300px"
            width="550px"
        >
            <div slot="title">模板说明</div>
            <div class="fontcolor" align="left" style="height: 260px">
                <table align="left">
                    <tr>
                        <td align="left">用户名称：使用系统的坐席姓名</td>
                    </tr>
                    <tr>
                        <td align="left">用户账户：登录系统的账号</td>
                    </tr>
                    <tr>
                        <td align="left">所属机构：坐席所在的机构名称</td>
                    </tr>
                    <tr>
                        <td align="left">用户类型：坐席角色类型，普通用户或者超级管理员</td>
                    </tr>
                    <tr>
                        <td align="left">系统话务工号：坐席所对应的AVAYA平台CTI工号，如：hs16001</td>
                    </tr>
                    <tr>
                        <td align="left">分机号：坐席所使用的AVAYA分机号</td>
                    </tr>
                    <tr>
                        <td align="left">手机号：可以联系到坐席的手机号码，比如坐席自己的手机号码</td>
                    </tr>
                    <tr>
                        <td align="left">黑名单：添加后客户可以进入IVR，但是不能转人工</td>
                    </tr>
                    <tr>
                        <td align="left">邮箱：坐席的公司邮箱或者私人邮箱</td>
                    </tr>
                    <tr>
                        <td align="left">备注：可对该坐席做一些特定的描述</td>
                    </tr>
                    <tr></tr>
                    <tr></tr>
                    <tr>
                        <td>
                            <div slot="footer" class="dialog-footer">
                                <el-button
                                    size="small"
                                    icon="el-icon-circle-close"
                                    @click="ShowImportTemp = false"
                                    class="cancelBtn"
                                >关 闭</el-button>
                            </div>
                        </td>
                    </tr>
                </table>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import Pagination from '@/components/Pagination/Pagination.vue';
import SelectTree from '@/components/SelectTree/SelectTree.vue';
import YsUpload from '@/components/YsUpload/YsUpload.vue';
import { RegConfig } from '@/utils/RegConfig';
import { getToken, getTokenHsbankNo } from '@/utils/auth';
import { random } from '@/utils/Common';
import request from '@/apis/request';
import { closePage, getDictSelectList, } from '@/utils/Common';

export default {
    name: 'userManagement',
    components: {
        Pagination,
        SelectTree,
        YsUpload,
    },
    data() {
        // 校验ag工号是否在区间内
        const validAgNum = (rule, value, callback) => {
            if (value !== '') {
                const params = {
                    lesseeCode: getTokenHsbankNo('HsbankNo'),
                    num: Number(value),
                    numParam: 'AG_NUM',
                };
                callback();
                // this.$post.IpAllocation.interval(params).then((res) => {
                //     if (res.data.success) {
                //         callback();
                //     } else {
                //         callback(res.data.msg);
                //     }
                // });
            } else {
                callback(new Error('请输入AG工号!'));
            }
        };
        // 校验cti工号是否在区间内
        const validCtiNum = (rule, value, callback) => {
            if (value !== '') {
                const params = {
                    lesseeCode: getTokenHsbankNo('HsbankNo'),
                    num: Number(value),
                    numParam: 'CTI_NUM',
                };
                callback();
                // this.$post.IpAllocation.interval(params).then((res) => {
                //     if (res.data.success) {
                //         callback();
                //     } else {
                //         callback(res.data.msg);
                //     }
                // });
            } else {
                callback(new Error('请输入cti工号!'));
            }
        };
        // 校验分机号是否在区间内
        const validExtensionNum = (rule, value, callback) => {
            if (value !== '') {
                const params = {
                    lesseeCode: getTokenHsbankNo('HsbankNo'),
                    num: Number(value),
                    numParam: 'EXTENSION_NUM',
                };
                callback();
                // this.$post.IpAllocation.interval(params).then((res) => {
                //     if (res.data.success) {
                //         callback();
                //     } else {
                //         callback(res.data.msg);
                //     }
                // });
            } else {
                callback(new Error('请输入分机号!'));
            }
        };
        return {
            editFlag: false,
            ShowImportTemp: false,
            formData: {
                userName: '',
                userAccount: '',
                workplaceId: '',
                ctiNum: '',
            },
            resetFlag: false,
            // 新增用户字段
            Edit: {
                userName: '',
                userAccount: '',
                agNum: '',
                ctiNum: '',
                ctiPass: '',
                userType: '0',
                extensionNum: '',
                workplaceId: '',
                deptId: '',
                userPhone: '',
                userEmail: '',
                labelCommunist: '',
                skillLevel: '',
                serverLevel: '',
            },
            EditTitle: '',
            Show: false,
            importShow: false,
            // 搜索loading
            searchLoading: false,
            // 重置loading
            resetLoading: false,
            formRules: {
                userName: [
                    { required: true, message: '请输入用户名称', trigger: 'blur' },
                    { max: 30, message: '字符最大长度为30', trigger: 'blur' },
                ],
                userAccount: [
                    { required: true, message: '请输入用户账号', trigger: 'blur' },
                    { max: 30, message: '字符最大长度为30', trigger: 'blur' },
                ],
                userType: [
                    { required: true, message: '请选择用户类型', trigger: 'change' },
                ],
                // agNum: [
                //     { required: true, message: '请输入AG工号', trigger: 'blur' },
                //     { pattern: /^\d{6}$/, message: '请输入6位的AG工号', trigger: 'blur' },
                //     { validator: validAgNum, trigger: 'blur' },
                // ],
                // ctiNum: [
                //     { required: true, message: '请输入CTI工号', trigger: 'blur' },
                //     { pattern: /^\d{7}$/, message: '请输入7位的CTI工号', trigger: 'blur' },
                //     { validator: validCtiNum, trigger: 'blur' },
                // ],
                // ctiPass: [
                //     { required: true, message: '请输入CTI工号登录密码', trigger: 'blur' },
                //     { max: 6, message: '字符最大长度为6', trigger: 'blur' },
                // ],
                // extensionNum: [
                //     { required: true, message: '请输入分机号', trigger: 'blur' },
                //     { pattern: /^\d{4}$/, message: '请输入7位的分机号', trigger: 'blur' },
                //     { validator: validExtensionNum, trigger: 'blur' },
                // ],
                // workplaceId: [
                //     { required: true, message: '请输入所属职场', trigger: 'change' },
                // ],
                deptId: [
                    { required: true, message: '请输入所属机构', trigger: 'change' },
                ],
                // userPhone: [
                //     { required: true, message: '请输入手机号码', trigger: 'blur' },
                //     { pattern: RegConfig.mobile, message: '请输入11位有效手机号码', trigger: 'blur' },
                // ],
                userEmail: [
                    { pattern: RegConfig.email, message: '请输入正确的邮箱号', trigger: 'blur' },
                ],
            },
            // 当前页码
            currentPage: 1,
            // 页码大小
            pageSize: 10,
            // 总数
            total: 0,
            // 表格内容
            tableData: [],
            workplaceList: [],
            departList: [],
            customerFlag: false,
            lesseeFlag: false,
            defaultProps: {
                parent: 'pid',
                value: 'id',
                label: 'deptName',
                children: 'child',
            },
            actionUrl: '/iccsrv/sys/user/importUser',
            serverLevelOption: {
                type: Array,
                default: [],
            },
        };
    },
    async mounted() {
        await this.getinit();
        this.getInitData(this.formData);
        this.$post.departManage.searchByDept({}).then((res) => {
            if (res.data.success) {
                this.departList = res.data.content;
            }
        }, (err) => {
            this.$message.error(err);
        });
        if (JSON.parse(getToken()).userType !== '0') {
            this.resetFlag = true;
        }
        if (JSON.parse(getToken()).userType === '2') {
            this.customerFlag = true;
        }
        if (JSON.parse(getToken()).userType === '1' || JSON.parse(getToken()).userType === '2') {
            this.lesseeFlag = true;
        }
        const params = {
            pageNum: 1,
            pageSize: 10,
        };
        this.$post.Workplace.searchWorkplace(params)
            .then((res) => {
                if (res.data.success) {
                    this.workplaceList = res.data.content.workplaceList;
                }
            });
    },
    methods: {
        async getinit() {
            this.serverLevelOption = await getDictSelectList('SERVER_LEVEL', this);
        },
        // 获取用户表格数据
        getInitData(form) {
            let params = {
                pageNum: this.currentPage,
                pageSize: this.pageSize,
            };
            params = Object.assign({}, params, form);
            this.$post.userManage.selectByUser(params)
                .then((res) => {
                    if (res.data.success) {
                        this.tableData = res.data.content.userList;
                        this.total = res.data.content.userCount;
                    }
                });
        },
        // 点击搜索
        hanlesearch() {
            this.currentPage = 1;
            this.pageSize = 10;
            this.getInitData(this.formData);
        },
        // 点击重置
        handleReset() {
            this.formData = {
                userName: '',
                userAccount: '',
                workplaceId: '',
                agNum: '',
            };
            this.currentPage = 1;
            this.pageSize = 10;
            this.getInitData(this.formData);
        },
        // 点击新增
        hanlePush() {
            this.editFlag = false;
            this.EditTitle = '添加用户';
            this.Edit = {};
            this.Show = true;
            this.Edit.agNum = random(111111, 999999);
            this.Edit.ctiPass = 'Teamsun01';
            this.Edit.workplaceId = '1';
            // 解决一进来就进行表单验证问题
            if (this.$refs.Edit) {
                console.log('this.$refs.Edit');
                this.$refs.Edit.resetFields();
            } else {
                this.$nextTick(() => {
                    // this.$refs.Edit.resetFields();
                });
            }
        },
        // 点击编辑
        handleEdit(row) {
            this.EditTitle = '修改用户';
            this.editFlag = true;
            this.Edit = JSON.parse(JSON.stringify(row));
            this.Show = true;
            if (this.$refs.Edit) {
                this.$refs.Edit.resetFields();
            } else {
                this.$nextTick(() => {
                    // this.$refs.Edit.resetFields();
                });
            }
        },
        // 密码重置
        handleResetPass(row) {
            this.$confirm('确认重置密码?', '提示', { customClass: 'warning', type: 'warning' })
                .then(() => {
                    this.$post.userManage.resetPwd(row).then((res) => {
                        if (res.data.success) {
                            this.$message.success('密码重置为：Aa123456 ');
                        }
                    });
                }).catch(() => { });
        },
        // 单个删除用户
        handleDelete(row) {
            this.$confirm('确认删除该用户？', '提示', { customClass: 'warning', type: 'warning' })
                .then(() => {
                    this.$post.userManage.deleteUser({ id: row.id })
                        .then((res) => {
                            if (res.data.success) {
                                this.$message.success('删除成功！');
                                if (this.tableData.length === 1) {
                                    this.currentPage = this.currentPage - 1;
                                }
                                this.getInitData(this.formData);
                            } else {
                                this.$message.error(res.data.msg);
                            }
                        });
                })
                .catch(() => {
                });
        },
        // 新增用户点击确定按钮
        submitEdit() {
            if (this.Edit.id) {
                // 编辑
                this.$refs.Edit.validate((valid) => {
                    if (valid) {
                        this.$post.userManage.updateUser(this.Edit)
                            .then((res) => {
                                if (res.data.success) {
                                    this.$message.success('修改成功！');
                                    this.getInitData(this.formData);
                                    this.Show = false;
                                } else {
                                    this.$message.error(res.data.msg);
                                }
                            });
                    } else {
                        this.$message.warning('请完成表单填写！');
                    }
                });
            } else {
                // 添加
                this.$refs.Edit.validate((valid) => {
                    if (valid) {
                        this.$post.userManage.addUser(this.Edit)
                            .then((res) => {
                                if (res.data.success) {
                                    this.$message.success('添加成功,初始密码为: Aa123456');
                                    this.getInitData(this.formData);
                                    this.Show = false;
                                } else {
                                    this.$message.error(res.data.msg);
                                }
                            });
                    } else {
                        this.$message.warning('请完成表单填写！');
                    }
                });
            }
        },

        // 点击导入
        clickImport() {
            this.importShow = true;
        },

        // 打开
        handleImport() {
            this.$refs.YsUpload.submitupload();
        },
        // 取消
        cancelClick() {
            // 执行文件列表清除方法
            this.$refs.YsUpload.clearFilesFun();
            this.importShow = false;
        },
        // 下载按钮
        downloadFile() {
            this.ShowImportTemp = true;
            const url = '/iccsrv/sys/user/userExport';
            request({
                url,
                method: 'get',
                responseType: 'blob',
                params: 'userTemplate.xlsx',
            }).then((res) => {
                const blobUrl = window.URL.createObjectURL(new Blob([res.data]));
                const a = document.createElement('a');
                a.style.display = 'none';
                a.download = 'userTemplate.xlsx';
                a.href = blobUrl;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
            });
        },

        // 页码切换方法
        hanleChangeCurrentPage(val) {
            this.currentPage = val;
            this.getInitData();
        },
        // 切换分页大小方法
        handleChangeSize(val) {
            this.pageSize = val;
            this.getInitData();
        },
    },
};
</script>

<style  lang="scss">
.fontcolor {
    padding-left: 5px;
    color: red;
}
.container {
    width: 100%;
    height: 100%;
    .userManageMain {
        width: 100%;
        background: #fff;
        margin-bottom: 15px;
        // border-radius:5px;
        padding: 20px;
        box-sizing: border-box;
        text-align: left;
        .tableTitle {
            width: 100%;
            height: 48px;
            border: 1px solid #eee;
            border-bottom: none;
            line-height: 48px;
            margin-top: 20px;
            color: #666;
        }
        .pagination {
            margin-top: 20px;
            text-align: right;
        }
    }
}
</style>
